package com.mainworks.commons.redis;

import com.mainworks.commons.constant.Constants;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Set;

/**
 * Redis 空键维护类
 * @Author: HuangMinJie
 * @CreateDate: 11:16 2021/10/29
 * @Description:
 * @Version: 1.0.0.0
 * @ModifiedBy:
 * @ModifiedDate:
 * @ModifiedDescription:
 */
public final class RedisNullKeys {

    public static final String cacheName = "null_keys";

    public static void put(RedisTemplate<String,String> redisTemplate,String key){
        long expire =System.currentTimeMillis() + Constants.RedisNullKeysExpire;
        redisTemplate.opsForHash().put(cacheName,key,String.valueOf(expire));
    }

    public static void deleteNullKey(RedisTemplate<String,String> redisTemplate){
        Set<Object> set = redisTemplate.opsForHash().keys(cacheName);
        long now =System.currentTimeMillis();
        for (Object obj:set){
            String value =(String) redisTemplate.opsForHash().get(cacheName,obj);
            long expire = Long.parseLong(value);
            if (now>expire){
                String key = (String) obj;
                String [] keys=key.split("_");
                redisTemplate.opsForHash().delete(keys[0],keys[1]);
                redisTemplate.opsForHash().delete(cacheName,obj);
            }
        }
    }
}
